package com.pearadmin.schedule.task;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.HashMap;

@Slf4j
@Component("LoginFeatuersInterceptor")
public class LoginFeatuersInterceptor implements HandlerInterceptor {
    @Resource
    private RestTemplate restTemplate;
    private Logger logger = LoggerFactory.getLogger(LoginFeatuersInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String features = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("userKeyFeatures")){
                features = cookie.getValue();
            }
        }
        //获取当前登录用户的用户名
        String name = request.getParameter("name");
        logger.debug("当前登录的用户的用户名为:"+name);
        //获取用户登录密码
        String password = request.getParameter("password");
        //获取用户输入特征
        logger.debug("获取的用户键盘特征为:"+URLDecoder.decode(features));
        //获取用户ip
        String ip = request.getRemoteAddr();
        //URLDecoder.decode(features)-->把cookie解码
        logger.debug("获取的用户密码为："+password);
        logger.debug("获取的用户ip为："+ip);
        //根据用户IP获取经纬度
        String ipUrl = "http://ip-api.com/json/"+"115.48.115.83";
        //使用map接收传递回来的数据.
        HashMap map = restTemplate.getForObject(ipUrl, HashMap.class);
        logger.debug("当前用户登录的经纬度为:"+map.get("lat")+"\t"+map.get("lon"));
        //获取用户登录设备
        String userEquipment = request.getHeader("User-Agent");
        logger.debug("当前用户登陆的设备:"+userEquipment);

        //flume采集日志的格式为:
        //用户名 密码 输入特征 用户ip 经纬度 登录设备
        logger.info(name+" "+password+" "+URLDecoder.decode(features)+" "+ip+" "+map.get("lat")+" "+map.get("lon")+" "+userEquipment);
        return true;
    }

}